
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "db_pgsql.h"

//static char db_hostaddr[32];
//static char db_port[32];
//static char db_user[32];
//static char db_pwd[32];
//static char db_name[32];

static PGconn *pg_connect;
static PGresult *pg_result;

// 连接数据库.
int db_connect()
{
    char connstr[256];

    bzero(connstr, sizeof(connstr));
    // 构造连接串.
//	snprintf(connstr, sizeof(connstr)-1,
//		"hostaddr=%s port=%s dbname=%s user=%s password=%s",
//		db_hostaddr, db_port, db_name, db_user, db_pwd);

    snprintf(connstr, sizeof(connstr)-1,
             "hostaddr=%s port=%s dbname=%s user=%s password=%s",
             "127.0.0.1", "5432", "test", "yuan", "yuanzc");

    // 连接数据库.
    pg_connect = PQconnectdb(connstr);
    // 查询连接状态.
    if(PQstatus(pg_connect) != CONNECTION_OK)
    {
        // 打印错误信息.
//		LOGOUT(4, "connect error :%s\n", PQerrorMessage(pg_connect));
        // 释放数据库连接.
        PQfinish(pg_connect);
        return -1;
    }

    return 0;
}

// 关闭数据库.
int db_close()
{
    // 清除执行结果.
    PQclear(pg_result);

    // 释放数据库连接
    PQfinish(pg_connect);

    return 0;
}

// 执行一次性 SQL 语句.
int db_exec(char *sql)
{
//	LOGOUT(4, "EXEC SQL : %s\n", sql);

    // 执行SQL语句,开始一个事务.
    pg_result = PQexec(pg_connect, sql);
    // 查询执行结果状态.
    if(PQresultStatus(pg_result) != PGRES_COMMAND_OK)
    {
        // 打印错误信息.
//		LOGOUT(4, "exec error :%s\n", PQerrorMessage(pg_connect));
        PQclear(pg_result);
        PQfinish(pg_connect);
        return -1;
    }

    // 清除执行结果.
    PQclear(pg_result);

    return 0;
}

// 执行SELECT, 结果集放入table中, 可放入rows行, cols列.
// 执行此函数时,注意SQL语句,不要一次取出太多数据.可以多取几次.
int db_get_set(char *sql, int *rows, int *cols)
{
//	LOGOUT(4, "GET SET SQL : %s\n", sql);

    // 执行SQL语句,开始一个事务.
    pg_result = PQexec(pg_connect, sql);
    // 查询执行结果状态.
    if(PQresultStatus(pg_result) != PGRES_TUPLES_OK)
    {
        // 打印错误信息.
//		LOGOUT(4, "exec error :%s\n", PQerrorMessage(pg_connect));
        PQclear(pg_result);
        PQfinish(pg_connect);
        return -1;
    }

    // 查询取出的字段数.
    *cols = PQnfields(pg_result);

    *rows = PQntuples(pg_result);

    if(*cols == 0 || *rows == 0)
    {
        return -1;
    }

    return 0;
}

int db_get_field(char *data, int len, int row, int col)
{
    int rows = PQntuples(pg_result);
    int cols = PQnfields(pg_result);
    char *p;

    if(cols == 0 || rows == 0)
    {
        return -1;
    }

    if(row > rows || col > cols)
    {
        return -1;
    }

    p = PQgetvalue(pg_result, row, col);
    if(p)
    {
        strncpy(data, p, len);
    }

    return 0;
}

int db_clear_result()
{
    // 清除执行结果.
    PQclear(pg_result);

    return 0;
}

int db_begin()
{
    PQexec(pg_connect, "BEGIN;");

    return 0;
}

int db_commit()
{
    PQexec(pg_connect, "COMMIT;");

    return 0;
}

int db_rollback()
{
    PQexec(pg_connect, "ROLLBACK;");

    return 0;
}